package 文件流.Thread;

/**
 * @author 王敬仟
 * 守护线程 多线程并发安全问题
 */
public class Dome {
    public static void main(String[] args) {
        //创建一个线程 演示守护线程
        Thread thread=new Thread(){
          public void run(){
              for (int i = 0; i < 3; i++) {
                  //循环输出3次"恭喜发财"
                  System.out.println("恭喜发财!");
                  try {
                      //阻塞5秒
                      Thread.sleep(5000);
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
              }
              System.out.println("抱拳!");
          }
        };
        Thread dog=new Thread(){
          public void run(){
              while (true){
                  System.out.println("愿你.桥都醒目,隧道都光明");
                  try {
                      //阻塞2秒
                      Thread.sleep(2000);
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
              }
          }
        };
        thread.start();//调用start方法执行线程
        dog.setDaemon(true);//设置守护线程
        dog.start();


        /*synchronized锁定代码块*/
        Shop shop=new Shop();
        Thread Tom=new Thread(){
          public void run(){
              shop.buy();
          }
        };
        Thread Jerry=new Thread(){
          public void run(){
              shop.buy();
          }
        };
        Tom.start();//调用start()执行线程
        Jerry.start();//调用start()执行线程
    }
}

class Shop{
    public void buy(){
        Thread t = Thread.currentThread();//获取线程
        try {
            System.out.println(t.getName()+":正在挑衣服...");
            Thread.sleep(5000);
            //进行上锁
            synchronized (this) {
                System.out.println(t.getName() + ":正在试衣服...");
                Thread.sleep(5000);
            }
            System.out.println(t.getName()+":结账离开");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
